package com.demo.easy.oneLine;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import static org.apache.poi.hssf.model.InternalWorkbook.createWorkbook;

/**
 * @Author:YuXuePeng
 * @Date:Created in 2023/4/14 17:51
 */
@RestController
//@RequestMapping("/sys")
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @RequestMapping("/import")
    public List<TemplateEntity> importData(@RequestParam("file") MultipartFile file) throws IOException {
        return templateService.importExcel(file);
    }

    @RequestMapping("/importDuo")
    public List<TemplateHeadlerEntity> importHeaderData(@RequestParam("file") MultipartFile file) throws IOException {
        return templateService.importHeadlerExcel(file);
    }

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    @RequestMapping("/download")
    public String download(HttpServletResponse response) throws IOException {
        String[] strs = {"张三","李四","王五","赵六"};
        int max = 20;
        int min = -10;
        List<TemplateEntity> list = new ArrayList<TemplateEntity>();
        for (int i = 0; i < 20; i++) {
            TemplateEntity templateEntity = new TemplateEntity();
            templateEntity.setLabel(i);
            templateEntity.setStr(strs[new Random().nextInt(strs.length)]);
            templateEntity.setNum(new Random().nextInt((max - min) + 1)+min);
            list.add(templateEntity);
        }
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "Red.xls";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));

        // 创建ExcelWriter对象
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(response.getOutputStream(), TemplateEntity.class)
                .registerWriteHandler(new IndexRedWriterHandle216());

        excelWriterBuilder.sheet().doWrite(list);
        return "导出成功";

    }
    @RequestMapping("/downloadRead")
    public String downloadRead(HttpServletResponse response) throws IOException {
        String[] strs = {"张三","李四","王五","赵六"};
        int max = 20;
        int min = -10;
        List<TemplateHeadlerEntity> list = new ArrayList<>();


        for (int i = 0; i < 20; i++) {
            TemplateHeadlerEntity templateHeadlerEntity = new TemplateHeadlerEntity();
            templateHeadlerEntity.setLabel(i+"");
            templateHeadlerEntity.setStr(strs[new Random().nextInt(strs.length)]);
            templateHeadlerEntity.setNum(new BigDecimal(new Random().nextInt((max - min) + 1)+min));
            templateHeadlerEntity.setDate(getRandomDate("2023-12-31"));
            list.add(templateHeadlerEntity);
        }
//         设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "Class.xls";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/templateDuoHeadler.xls");
        Workbook workbook = writeData(resourceAsStream, list);
        workbook.write(response.getOutputStream());


        // 创建ExcelWriter对象
//        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(response.getOutputStream(), TemplateEntity.class)
//                .registerWriteHandler(new IndexRedWriterHandle216());
//
//        excelWriterBuilder.sheet().doWrite(list);
        return "导出成功";

    }
    private String getRandomDate(String maxdate){
        LocalDate minDate = LocalDate.of(2020, 1, 1); // 指定最小日期为2020年1月1日
        LocalDate maxDate = LocalDate.parse(maxdate); // 指定最大日期为2022年12月31日
        long minDay = minDate.toEpochDay(); // 将最小日期转换为距离1970年1月1日的天数
        long maxDay = maxDate.toEpochDay(); // 将最大日期转换为距离1970年1月1日的天数
        long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay + 1); // 生成随机日期
        LocalDate randomDate = LocalDate.ofEpochDay(randomDay); // 将随机日期转换为LocalDate对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 指定日期格式为“年-月-日”
        String formattedDate = randomDate.format(formatter); // 格式化日期为指定字符串格式
        System.out.println(formattedDate); // 输出随机日期
        return formattedDate;
    }
    private Workbook writeData(InputStream inputStream,List list) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).inMemory(Boolean.TRUE).withTemplate(inputStream).excelType(ExcelTypeEnum.XLS).registerWriteHandler(new IndexRedWriterHandle216()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        excelWriter.finish();
        ByteArrayInputStream swapStream = new ByteArrayInputStream(outputStream.toByteArray());
        Workbook workbook = createWorkBook(swapStream,ExcelTypeEnum.XLS);
        return workbook;
    }
    public Workbook createWorkBook(InputStream templateInputStream, ExcelTypeEnum excelType) throws IOException {
        Workbook workbook;
        if (ExcelTypeEnum.XLS.equals(excelType)) {
            workbook = (templateInputStream == null) ? new HSSFWorkbook() : new HSSFWorkbook(
                    new POIFSFileSystem(templateInputStream));
        } else {
            workbook = (templateInputStream == null) ? new SXSSFWorkbook(500) : new XSSFWorkbook(templateInputStream);
        }
        return workbook;
    }
}
